package org.hdax.easybuygateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("网关过滤器执行了");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getHeader("token");
        if (token == null){
            requestContext.setSendZuulResponse(false);//终止运行
            requestContext.setResponseStatusCode(401);//http状态码
            requestContext.getResponse().setContentType("text/json;charset=UTF‐8");
            try {

                requestContext.setResponseBody(new String("{msg:'你还没有登录呢',code:0}".getBytes("utf-8"), "iso8859-1"));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
